package com.xianbeiying.app.ckgl.widght;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.xianbeiying.app.ckgl.R;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 图片查看器
 *
 * @author wyf
 */
public class MyImageBrowser extends FrameLayout {

    private List<MyImageView> views;
    private PagerAdapter adapter;
    private MyViewPager viewPager;
    //	private View optionBar;
//	private boolean useOptionBar = true; //记录菜单条使用情况，实现长时间不用则隐藏菜单条
//	private TextView pageNumView;
//	private boolean playState = false; //幻灯片播放状态
    private final int playInterval = 5000; //幻灯片播放间隔时间毫秒值
    private Timer timer;
    private TimerTask timerTask; //用于幻灯片播放
    private Handler handler; //用于非ui线程中执行特殊方法

    private OnDongzuoListener pageChgLst;

    private Bitmap loadingBmp, potuBmp;


    public MyImageBrowser(Context context) {
        super(context);
        init();
    }

    public MyImageBrowser(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        timer = new Timer();
        handler = new Handler();

        viewPager = new MyViewPager(this.getContext());
        this.addView(viewPager, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//加载中
        loadingBmp = BitmapFactory.decodeResource(this.getResources(), R.mipmap.img_default4);
//        加载失败
        potuBmp = BitmapFactory.decodeResource(this.getResources(), R.mipmap.img_default4);

//		optionBar = LayoutInflater.from(this.getContext()).inflate(R.layout.imagebrowser_optionbar, this, false);
//		this.addView(optionBar);
//		//一定时间选项条不使用自动隐藏
//		timer.schedule(new TimerTask(){
//			@Override
//			public void run() {
//				handler.post(new Runnable(){
//					@Override
//					public void run() {
//						if(optionBar.getVisibility() == View.VISIBLE)
//						{
//							if(!useOptionBar)
//							{
//								optionBar.setVisibility(INVISIBLE);
//							}
//							useOptionBar = false;
//						}
//					}});
//			}}, 4000, 4000);

//		optionBar.findViewById(R.id.saveBtn).setOnClickListener(this);
//		optionBar.findViewById(R.id.prevBtn).setOnClickListener(this);
//		optionBar.findViewById(R.id.playBtn).setOnClickListener(this);
//		optionBar.findViewById(R.id.nextBtn).setOnClickListener(this);
//		optionBar.findViewById(R.id.zoomInBtn).setOnClickListener(this);
//		optionBar.findViewById(R.id.zoomOutBtn).setOnClickListener(this);
//		pageNumView = (TextView)optionBar.findViewById(R.id.pageNumView);
//		optionBar.findViewById(R.id.btn_del).setOnClickListener(this);
//		optionBar.findViewById(R.id.wallpaperBtn).setOnClickListener(this);
//		optionBar.findViewById(R.id.lturnBtn).setOnClickListener(this);
//		optionBar.findViewById(R.id.rturnBtn).setOnClickListener(this);

        views = new ArrayList<MyImageView>();

        //翻页时的回调监听
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            private int cPage; //记录当前页
            private int rPage; //记录上一页

            @Override
            public void onPageScrollStateChanged(int arg0) {
//				Log.d(MyApp.LOGTAG, "onPageScrollStateChanged "+arg0);

                if (arg0 == 0)  //滚动停止时
                {
                    //还原上一张图片大小
                    if (rPage < views.size())
                        views.get(rPage).reHeshiScale();

                    //执行切换时，若上一个图片是第一张或者最后一张，同步两头的图片状态
                    if (rPage == 1) {
                        MyImageView v1 = views.get(views.size() - 1);
                        MyImageView v2 = views.get(1);
                        v1.copyState(v2);
                    }
                    if (rPage == views.size() - 2) {
                        MyImageView v1 = views.get(0);
                        MyImageView v2 = views.get(views.size() - 2);
                        v1.copyState(v2);
                    }

                    //实现循环切换图片
                    if (views.size() > 1) {
                        if (cPage == 0)
                            viewPager.setCurrentItem(views.size() - 2, false);
                        else if (cPage == views.size() - 1)
                            viewPager.setCurrentItem(1, false);
                    }
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
//				Log.d(MyApp.LOGTAG, "onPageScrolled " + arg0 + " " + arg1 + " " + arg2);
            }

            @Override
            public void onPageSelected(int arg0) {
//				Log.d(MyApp.LOGTAG, "onPageSelected "+arg0);
                rPage = cPage;
                cPage = arg0;

                if (pageChgLst != null) {
                    if (cPage == 0)
                        pageChgLst.onPageChange(views.size() - 3);
                    else if (cPage == views.size() - 1)
                        pageChgLst.onPageChange(0);
                    else
                        pageChgLst.onPageChange(cPage - 1);
                }
//					pageNumView.setText(cPage+"/"+(views.size()-2));  //更改界面上的当前页码号

            }
        });
    }


    public static interface OnDongzuoListener {
        /**
         * 切换页面时调用
         *
         * @param cPage 当前页码
         */
        public void onPageChange(int cPage);

        /**
         * 图片的单击事件
         *
         * @param v
         */
        public void onSigclicked(View v);
    }


    /**
     * 释放所占用的资源，确定不再使用
     */
    public void release() {
        timer.cancel();
        timer = null;
        timerTask = null;
        for (MyImageView v : views) {
            v.releaseBitmap();
        }
        views.clear();
        views = null;
        loadingBmp.recycle();
        loadingBmp = null;
    }

    /**
     * 设置要浏览的图片集
     *
     * @param imgFiles
     */
    public void setImages(String[] imgFiles, int currentPage) {
        views.clear();
        if (imgFiles.length == 0)
            return;
        //为了实现图片循环切换,两头多加第一张和最后一张
        if (imgFiles.length > 1)
            views.add(new MyImageView(this.getContext(), imgFiles[imgFiles.length - 1]));
        for (String file : imgFiles) {
            views.add(new MyImageView(this.getContext(), file));
        }
        if (imgFiles.length > 1)
            views.add(new MyImageView(this.getContext(), imgFiles[0]));

//		viewPager.removeAllViews();
        //初始化ViewPager的适配器
        adapter = new PagerAdapter() {

            @Override
            public int getCount() {
                return views.size();
            }

            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }

            @Override
            public Object instantiateItem(View collection, int position) {
                MyImageView v = views.get(position);
                ((ViewPager) collection).addView(v);
                v.createBitmap();
                return v;
            }

            @Override
            public void destroyItem(View collection, int position, Object o) {
//				MyImageView v = views.get(position);
                MyImageView v = (MyImageView) o;
                Log.d("fffffffff", "destroyItem");
//						v.matrix.set(v.heshiMatrix);
                ((ViewPager) collection).removeView(v);
                v.releaseBitmap();
            }

//			@Override
//		    public int getItemPosition(Object object)
//			{
//				return POSITION_NONE;
//			}
        };
        viewPager.setAdapter(adapter);
//		adapter.notifyDataSetChanged();
        if (views.size() > 1)
            viewPager.setCurrentItem(currentPage + 1, false);
    }

    /**
     * 返回当前页码
     *
     * @return
     */
    public int getCurrentPage() {
        return viewPager.getCurrentItem();
    }

//	/**
//	 * 显示或隐藏选项菜单条
//	 */
//	public void toggleOptionBar()
//	{
//		if(optionBar.getVisibility() == View.VISIBLE)
//			optionBar.setVisibility(View.INVISIBLE);
//		else
//		{
//			optionBar.setVisibility(View.VISIBLE);
//			useOptionBar = true;
//			stopPlay(); //停止幻灯片播放
//		}
//	}

    /**
     * 切换到上一张图片
     */
    public void prevPage() {
        viewPager.setCurrentItem(viewPager.getCurrentItem() - 1, true);
    }

    /**
     * 切换到下一张图片
     */
    public void nextPage() {
        viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
    }

    /**
     * 播放幻灯片
     */
    public void play() {
        //实现幻灯片播放
        if (timerTask != null) {
            timerTask.cancel();
            timer.purge();
        }
        timerTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        nextPage();
                    }
                });
            }
        };
        timer.schedule(timerTask, playInterval / 2, playInterval);
//		optionBar.setVisibility(View.INVISIBLE); //选项菜单隐藏
        Toast.makeText(this.getContext(), "开始播放幻灯片", Toast.LENGTH_LONG).show();
    }

    /**
     * 幻灯片播放停止
     */
    public void stopPlay() {
        if (timerTask != null) {
            timerTask.cancel();
            timer.purge();
            timerTask = null;
            Toast.makeText(this.getContext(), "幻灯片停止播放", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 返回幻灯片是否正在播放
     *
     * @return
     */
    public boolean isPlaying() {
        return timerTask != null;
    }

    /**
     * 缩放当前页的图片
     *
     * @param s 缩放比例
     */
    public void zoom(float s) {
        MyImageView v = views.get(viewPager.getCurrentItem());
        v.zoom(s, new PointF(v.getWidth() / 2, v.getHeight() / 2));
    }

    /**
     * 旋转当前图片
     *
     * @param rotate 旋转角度
     */
    public void rotate(int rotate) {
        views.get(viewPager.getCurrentItem()).rotate(rotate);
    }

//	/**
//	 * 保存当前页的图片
//	 */
//	public void saveImage()
//	{
//		if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
//		{
//			Toast.makeText(this.getContext(), "保存失败！内存卡不可用", Toast.LENGTH_SHORT).show();
//			return;
//		}
//		String path = "/sdcard/美图收藏/";
//		File dir = new File(path);
//		if(!dir.exists())
//			dir.mkdir();
//		MyImageView v = views.get(viewPager.getCurrentItem());
//		String fileName = v.file.substring(v.file.lastIndexOf('/')+1) + ".jpg";
//		FileOutputStream out = null;
//		try {
//			out = new FileOutputStream(path+fileName);
//			if(v.bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out))
//				Toast.makeText(this.getContext(), "图片已保存到"+path, Toast.LENGTH_SHORT).show();
//			else
//				Toast.makeText(this.getContext(), "图片保存失败！请重试", Toast.LENGTH_SHORT).show();
//		} catch (FileNotFoundException e) {
//			Log.e("fffff", e.getMessage(), e);
//			Toast.makeText(this.getContext(), "图片保存失败！请检查内存卡是否插入", Toast.LENGTH_SHORT).show();
//		}finally
//		{
//			try {
//				if(out != null)
//					out.close();
//			} catch (IOException e) {
//				Log.e("ffff", e.getMessage(), e);
//			}
//		}
//	}

//	/**
//	 * 将当前页图片设为壁纸
//	 */
//	public void setWallpaper()
//	{
//		new Thread(new Runnable(){
//			@Override
//			public void run() {
//				try {
//					MyImageBrowser.this.getContext()
//						.setWallpaper(views.get(viewPager.getCurrentItem()).bitmap);
//					handler.post(new Runnable(){
//						@Override
//						public void run() {
//							Toast.makeText(MyImageBrowser.this.getContext(), "壁纸设置成功",
//									Toast.LENGTH_SHORT).show();
//						}});
//				} catch (IOException e) {
//					Log.e("fffff", e.getMessage(), e);
//				}
//			}}).start();
//	}

//	@Override
//	public void onClick(View v) {
////		useOptionBar = true;
//		switch(v.getId())
//		{
//		case R.id.saveBtn:
//				new AlertDialog.Builder(this.getContext())
//					.setTitle("保存图片").setIcon(R.drawable.single_view_send_n)
//					.setMessage("确定将图片保存到内存卡吗？")
//					.setPositiveButton(R.string.ok,new DialogInterface.OnClickListener(){
//						public void onClick(DialogInterface dialog, int which) {
//							saveImage();
//						}})
//					.setNegativeButton(R.string.cancel, null)
//					.show();
//			break;
//		case R.id.prevBtn:
//			prevPage();
//			break;
//		case R.id.playBtn:
//			play();
//			break;
//		case R.id.nextBtn:
//			nextPage();
//			break;
//		case R.id.zoomInBtn:
//			zoom(1.25f);
//			break;
//		case R.id.zoomOutBtn:
//			zoom(0.8f);
//			break;
//		case R.id.wallpaperBtn:
//				new AlertDialog.Builder(this.getContext())
//					.setTitle("设置壁纸").setIcon(R.drawable.single_view_apply_n)
//					.setMessage("确定要将此图片设为壁纸吗？")
//					.setPositiveButton(R.string.ok,new DialogInterface.OnClickListener(){
//						public void onClick(DialogInterface dialog, int which) {
//							setWallpaper();
//						}})
//					.setNegativeButton(R.string.cancel, null)
//					.show();
//			break;
//		case R.id.lturnBtn:
//			rotate(-90);
//			break;
//		case R.id.rturnBtn:
//			rotate(90);
//			break;
//
//		case R.id.btn_del:
//			break;
//		}
//	}

    /**
     * 图片容器，实现分页切换浏览
     */
    private class MyViewPager extends ViewPager {
        private float pX; //记录上次触摸点x坐标

        public MyViewPager(Context context) {
            super(context);
        }

        @Override
        public boolean onInterceptTouchEvent(MotionEvent arg0) {
            if (arg0.getAction() == MotionEvent.ACTION_MOVE) {
                MyImageView v = views.get(this.getCurrentItem());
                if (v.tranX < 0) {
                    //屏蔽向右的滑动
                    if (arg0.getX() > pX)
                        return false;
                }
                if (v.getImgWidth() * v.scale + v.tranX > v.getWidth()) {
                    //屏蔽向左的滑动
                    if (arg0.getX() < pX)
                        return false;
                }
            }

            pX = arg0.getX();
            return super.onInterceptTouchEvent(arg0);
        }


        @Override
        public boolean onTouchEvent(MotionEvent arg0) {
            if (arg0.getAction() == MotionEvent.ACTION_MOVE) {
                MyImageView v = views.get(this.getCurrentItem());
                if (v.tranX < 0) {
                    //屏蔽向右的滑动
                    if (arg0.getX() > pX)
                        return false;
                }
                if (v.getImgWidth() * v.scale + v.tranX > v.getWidth()) {
                    //屏蔽向左的滑动
                    if (arg0.getX() < pX)
                        return false;
                }
            }

            pX = arg0.getX();
            return super.onTouchEvent(arg0);
        }
    }


    /**
     * 呈现图片的基本视图，实现了图片的缩放，拖动等
     */
    private class MyImageView extends View {
        private Paint paint;
        private Bitmap bitmap;
        private String file;
        private Matrix matrix;
        //		private boolean dblState; //双击放大状态
//		private Matrix heshiMatrix; //图片最合适的缩放
//		private Matrix dblMatrix; //双击后的放大效果
//		private boolean drag = true; //是否可拖拽
        private float touchJuli; //记录上次事件两触摸点之间的距离
        private float pX = -1, pY = -1; //记录上次事件触摸点的位置
        private float downX, downY; //记录按下时的位置

        private float scale; //当前缩放比例
        //		private float heshiScale;//最合适显示比例
//		private float dblScale; //双击后放大显示比例
        private float tranX, tranY; //当前偏移量
        private int rotate; //旋转角度
//		private int realWidth,realHeight; //图片的实际像素
//		private int heshiWidth,heshiHeight; //图片最合适的显示大小

        private boolean isRelease;

        public MyImageView(Context context, String file) {
            super(context);
            this.file = file;
//			createBitmap();
            paint = new Paint();
            paint.setColor(0xffffff00); //画线颜色
            paint.setStrokeWidth(5); //线条宽度
            matrix = new Matrix();

            this.setOnClickListener(new OnClickListener() {
                private long time;
                private Timer timer = new Timer();
                private Handler handler = new Handler();
                private TimerTask task;

                @Override
                public void onClick(final View v) {
                    Log.d("fff", "点击事件");

                    long now = System.currentTimeMillis();
                    if (now - time < 200) {
                        //双击
                        Log.d("ffff", "双击执行");
                        task.cancel();

                        dblClick();
                    } else {
                        //延迟执行单击
                        task = new TimerTask() {
                            @Override
                            public void run() {
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        //单击事件
                                        Log.d("fff", "单击执行");
//										sigClick();
                                        pageChgLst.onSigclicked(v);
                                    }
                                });
                            }
                        };
                        timer.schedule(task, 230);
                    }

                    time = now;
                }
            });
        }

        /**
         * 构建位图
         */
        public void createBitmap() {
            isRelease = false;
//			try {
            if (bitmap == null) {
//					bitmap = BitmapFactory.decodeStream(this.getContext().getAssets().open(file));
                bitmap = Cache.fromCache(file);
                if (bitmap == null) {
                    bitmap = loadingBmp;
                    //另起一个线程加载图片
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Bitmap bmp = Cache.getBitMapFromUrl(file);
                            if (bmp != null)
                                bitmap = bmp;
                            else
                                bitmap = potuBmp;
                            if (isRelease) {
                                releaseBitmap();
                                return;
                            }
                            scale = getHeshiScale();
                            postInvalidate();
                        }
                    }).start();
                }
                scale = getHeshiScale();
//					realWidth = bitmap.getWidth();
//					realHeight = bitmap.getHeight();
//					Log.d(MyApp.LOGTAG, "图宽："+realWidth+" 高:"+realHeight);
            }
//			} catch (IOException e) {
//				Log.e("ffff", e.getMessage(), e);
//			}
        }

        /**
         * 释放位图所占用的内存
         */
        public void releaseBitmap() {
            isRelease = true;
            if (bitmap != null && bitmap != loadingBmp && bitmap != potuBmp) {
                bitmap.recycle();
                bitmap = null;
            }
        }

        //		//单击执行
//		private void sigClick()
//		{
//			toggleOptionBar();
//		}
        //双击执行
        private void dblClick() {
            if (scale != this.getHeshiScale())
                scale = this.getHeshiScale();
            else {
                scale = this.getDblScale();
                toCenter();
            }
            this.invalidate();
        }

        //使图片居中
        private void toCenter() {
            tranX = (this.getWidth() - this.getImgWidth() * scale) / 2;
            tranY = (this.getHeight() - this.getImgHeight() * scale) / 2;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            if (isRelease)
                return;
            if (bitmap == null)
                this.createBitmap();
            //限制最小缩放比例
            if (scale == 0)
                scale = this.getHeshiScale();
//			else if(scale < this.getHeshiScale()/2)
//				scale = this.getHeshiScale()/2;
            //限制左右偏移位置
            if (this.getImgWidth() * scale < this.getWidth())
                tranX = (this.getWidth() - this.getImgWidth() * scale) / 2;
            else if (tranX > 0)
                tranX = 0;
            else if (tranX < this.getWidth() - this.getImgWidth() * scale)
                tranX = this.getWidth() - this.getImgWidth() * scale;
            //限制上下偏移位置
            boolean topLine = false, bottomLine = false;
            if (this.getImgHeight() * scale <= this.getHeight())
                tranY = (this.getHeight() - this.getImgHeight() * scale) / 2;
            else if (tranY > 0) {
                tranY = 0;
                topLine = true; //顶部绘制一条线表示上边已显示到边界
            } else if (tranY < this.getHeight() - this.getImgHeight() * scale) {
                tranY = this.getHeight() - this.getImgHeight() * scale;
                bottomLine = true; //底部绘制一条线表示下边已显示到边界
            }

            matrix.reset();
            matrix.postRotate(rotate, this.bitmap.getWidth() / 2, this.bitmap.getHeight() / 2);
            if (rotate / 90 % 2 != 0)
                matrix.postTranslate((this.getImgWidth() - this.getImgHeight()) / 2,
                        -(this.getImgWidth() - this.getImgHeight()) / 2);
            matrix.postScale(scale, scale);
            matrix.postTranslate(tranX, tranY);

            canvas.drawBitmap(bitmap, matrix, paint);

//			//绘制所需的提示线条
//			if(topLine)
//			{
//				canvas.drawLine(0, 0, this.getWidth(), 0, paint);
//				this.invalidate(); //重绘画面以消除此线条
//			}
//			if(bottomLine)
//			{
//				canvas.drawLine(0, this.getHeight()-1, this.getWidth(), this.getHeight()-1, paint);
//				this.invalidate(); //重绘画面以消除此线条
//			}
        }

//		@Override
//		protected void onSizeChanged(int w, int h, int oldw, int oldh) {
//			super.onSizeChanged(w, h, oldw, oldh);
////			if(bitmap == null)
////				createBitmap();
////			float wb = w/(float)this.getImgWidth(); //容器宽与图片宽的比例
////			float hb = h/(float)realHeight;  //容器高与图片高的比例
////			heshiScale = wb>hb?hb:wb;  //取其较小值
////			if(heshiScale > 1)
////				heshiScale = 1;
////			if(scale == 0)
////				scale = heshiScale;
////
////			dblScale = heshiScale * 2;
////			if(dblScale < 1)
////				dblScale = 1;
//		}

        //根据图片选择角度获得图宽
        private int getImgWidth() {
            if (bitmap == null)
                this.createBitmap();
            if (rotate / 90 % 2 == 0)
                return bitmap.getWidth();
            else
                return bitmap.getHeight();
        }

        //根据图片选择角度获得图高
        private int getImgHeight() {
            if (bitmap == null)
                this.createBitmap();
            if (rotate / 90 % 2 == 0)
                return bitmap.getHeight();
            else
                return bitmap.getWidth();
        }

        //获得合适缩放比例
        private float getHeshiScale() {
            float wb = this.getWidth() / (float) getImgWidth(); //容器宽与图片宽的比例
            float hb = this.getHeight() / (float) getImgHeight();  //容器高与图片高的比例
            float heshiScale = wb > hb ? hb : wb;  //取其较小值
//			if(heshiScale > 1)     //小图是否放大显示
//				heshiScale = 1;

            return heshiScale;
        }

        //获得双击放大的比例
        private float getDblScale() {
            float dblScale = this.getHeshiScale() * 2;
            if (dblScale < 1)
                dblScale = 1;
            return dblScale;
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            int pCount = event.getPointerCount();
//			Log.d(MyApp.LOGTAG, "触摸点数量:"+pCount);
            int action = event.getAction() & MotionEvent.ACTION_MASK;
//			Log.d(MyApp.LOGTAG, "action:"+action);

            if (pCount > 1) {
                switch (action) {
                    case MotionEvent.ACTION_POINTER_DOWN:
//					Log.d(MyApp.LOGTAG, "ACTION_POINTER_DOWN");
                        pX = -1;
                        pY = -1;
                        touchJuli = 0;
                        break;
                    case MotionEvent.ACTION_MOVE:
//					Log.d(MyApp.LOGTAG, "ACTION_MOVE");
                        PointF a = new PointF(event.getX(0), event.getY(0));
                        PointF b = new PointF(event.getX(1), event.getY(1));
                        float newJuli = this.getJuli(a, b);
                        if (touchJuli > 0) {
                            float zx = (a.x + b.x) / 2; //中点坐标
                            float zy = (a.y + b.y) / 2; //中点坐标
                            float s = newJuli / touchJuli;
                            zoom(s, new PointF(zx, zy));
                        }
                        touchJuli = newJuli;
                        break;
                    case MotionEvent.ACTION_POINTER_UP:
                        if (scale < this.getHeshiScale())
                            huitan();

//					Log.d(MyApp.LOGTAG, "ACTION_POINTER_UP");
                        touchJuli = 0;
                        break;
                }
            } else {
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
//					Log.d(MyApp.LOGTAG, "ACTION_DOWN");
                        downX = event.getX();
                        downY = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
//					Log.d(MyApp.LOGTAG, "ACTION_MOVE");
                        if (pX != -1 && pY != -1) {
                            tranX += event.getX() - pX;
                            tranY += event.getY() - pY;
                        }
//						matrix.postTranslate(event.getX()-pX, event.getY()-pY);
                        this.invalidate();
                        break;
                    case MotionEvent.ACTION_UP:
                        if (scale < this.getHeshiScale())
                            huitan();

//					Log.d(MyApp.LOGTAG, "ACTION_UP");
                        //若长按后弹起则屏蔽点击事件
                        if (event.getEventTime() - event.getDownTime() > 300)
                            return true;
                        //滑动手势也屏蔽点击事件
                        if (Math.abs(event.getX() - downX) > 10 || Math.abs(event.getY() - downY) > 10)
                            return true;

                        break;
                }
                pX = event.getX();
                pY = event.getY();
            }

            return super.onTouchEvent(event);
        }

        //计算两点之间距离
        private float getJuli(PointF a, PointF b) {
            float x = a.x - b.x;
            float y = a.y - b.y;
//            sqrt(x * x + y * y);
            return (float) Math.sqrt(x * x + y * y);
        }

        /**
         * 图片回弹到正常大小
         */
        private void huitan() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (; scale < getHeshiScale(); scale += 0.1) {
                        postInvalidate();
                    }
                    scale = getHeshiScale();
                    postInvalidate();
                }
            }).start();
        }

        /**
         * 缩放图片
         *
         * @param s 缩放比例
         * @param p 缩放所依据的中心点
         */
        public void zoom(float s, PointF p) {
            scale *= s;
            tranX *= s;
            tranX += p.x - p.x * s;
            tranY *= s;
            tranY += p.y - p.y * s;
            this.invalidate();
        }

        /**
         * 旋转图片
         *
         * @param rotate 旋转的角度
         */
        public void rotate(int rotate) {
            this.rotate += rotate;
            reHeshiScale();
        }

        /**
         * 还原图片为合适大小
         */
        public void reHeshiScale() {
            this.scale = this.getHeshiScale();
            this.invalidate();
        }

        /**
         * 从另一个图片视图复制状态
         *
         * @param other
         */
        public void copyState(MyImageView other) {
            this.scale = other.scale;
            this.tranX = other.tranX;
            this.tranY = other.tranY;
            this.rotate = other.rotate;
        }
    }

    public void setPageChgLst(OnDongzuoListener pageChgLst) {
        this.pageChgLst = pageChgLst;
    }

    public static class Cache {
        /**
         * 根据一个URL加载图片 完整的缓存机制
         *
         * @param url
         * @return
         */
        public static Bitmap getBitMapFromUrl(String url) {
            Bitmap bmp = fromCache(url);
            if (bmp != null)
                return bmp;

            bmp = writeCache(url);
            if (bmp != null)
                return bmp;

            //内存卡不可用,无法实现缓存机制
            try {
                bmp = fromNet(url);  //直接加载网络图片
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return bmp;
        }

        /**
         * 尝试写缓存,并得到图片
         *
         * @param url
         * @return
         */
        public static Bitmap writeCache(String url) {
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                File file = getCacheFile(url);
                //下载并保存文件
                try {
                    file.getParentFile().mkdirs();
                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                    int len = 2048;
                    byte[] b = new byte[len];
                    while ((len = bis.read(b)) != -1)
                        bos.write(b, 0, len);
                    bos.flush();
                    bos.close();
                    bis.close();
                    conn.disconnect();

//		            file.deleteOnExit(); //临时文件 退出时删除掉
                    //从文件加载图片
                    return fromFile(file);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }

        private static final String CPATH = "/miaos/ch/";

        //根据URL算出缓存文件路径
        private static File getCacheFile(String url) {
            String path = Environment.getExternalStorageDirectory() + CPATH;
            String[] ss = url.split("/");
            String filename = ss[ss.length - 2] + ss[ss.length - 1] + "m";
            File file = new File(path + filename);
            return file;
        }
        /**直接加载
         * */
         public static Bitmap imgBitp(Bitmap bitmap) {
          return bitmap;
         }
        /**
         * 直接尝试从缓存取图片
         *
         * @param url
         * @return
         */
        public static Bitmap fromCache(String url) {
            Bitmap bmp = null;
            File afile = new File(url);
            if (afile.exists())  //如果URL本身就是一个本地文件路径则直接加载文件就行了
            {
                try {
                    bmp = fromFile(afile);
                    return bmp;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                File file = getCacheFile(url);
                if (file.exists()) {
                    //从缓存文件加载图片
                    try {
                        bmp = fromFile(file);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            return bmp;
        }

        //从文件加载图片
        private static Bitmap fromFile(File file) throws IOException {
            InputStream is = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len = -1;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            while ((len = is.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            byte[] imgdata = outputStream.toByteArray();
            outputStream.close();
            is.close();

            return fromByteArray(imgdata);
        }

        //从网络加载图片
        private static Bitmap fromNet(String url) throws MalformedURLException, IOException {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            InputStream is = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            while ((len = is.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            byte[] imgdata = outputStream.toByteArray();
            outputStream.close();
            is.close();

            return fromByteArray(imgdata);
        }

        //字节数组解码生成bitmap
        private static Bitmap fromByteArray(byte[] imgdata) {
            Bitmap bitmap;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            bitmap = BitmapFactory.decodeByteArray(imgdata, 0, imgdata.length, options);
            int mianji = options.outHeight * options.outWidth;
            WindowSizeEntity wse = AppManager.getInstance().getWindowSizeEntity();
            double s = (double) mianji / (wse.getWidth() * wse.getHeight());
            if (s > 1)
                options.inSampleSize = (int) Math.sqrt(s);
            options.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeByteArray(imgdata, 0, imgdata.length, options);
            return bitmap;
        }

        /**
         * 清理缓存目录
         */
        public static void clear() {
            String path = Environment.getExternalStorageDirectory() + CPATH;
            File p = new File(path);
            if (p.listFiles() != null)
                for (File f : p.listFiles()) {
                    f.delete();
                }
        }
    }

}
